using System;
using System.Collections;
using System.Linq.Expressions;
using System.Windows.Controls;
using FluentSilverlight.Utility.Reflection;

namespace FluentSilverlight.Expressions.Lists
{
    public abstract class ItemsControlExpression<THIS, TModel> : ControlExpression<THIS, TModel, ItemsControl>
        where THIS : ItemsControlExpression<THIS, TModel>
        where TModel : class
    {
        private readonly TModel model;
        private IEnumerable itemsSource;

        protected ItemsControlExpression(TModel model)
        {
            this.model = model;
        }

        protected ItemsControlExpression(TModel model, string name)
            : base(name)
        {
            this.model = model;
        }

        public THIS ItemsSource(Expression<Func<TModel, object>> expression)
        {
            var expressionAccessor = ReflectionHelper.GetAccessor(expression);
            itemsSource = (IEnumerable)expressionAccessor.GetValue(model);
            return thisInstance();
        }

        protected override void BuildUp(ItemsControl element)
        {
            base.BuildUp(element);

            if (itemsSource != null)
                element.ItemsSource = itemsSource;
        }
    }
}